package com.globallogic.vkulyk.SSHTool;

import java.util.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jcraft.jsch.Session;

public class ActionsOnSocketsExecutor {

	private List<SocketDataKeeper> sockets;
	private List<ActionDataKeeper> actions;

	private SocketDataKeeper socketData = null;
	private ActionDataKeeper actionData = null;
	private ActionExecutor actionExecutor = null;

	private Session session = null;
	private String previousSessionID = "";

	private final Logger logger = LoggerFactory
			.getLogger(ActionsOnSocketsExecutor.class);

	public ActionsOnSocketsExecutor(List<SocketDataKeeper> sockets,
			List<ActionDataKeeper> actions) {
		this.sockets = sockets;
		this.actions = actions;
	}

	public void execute() {
		logger.debug("Started execution of action(s) on socket(s).");
		for (SocketDataKeeper socketData : sockets) {
			this.socketData = socketData;
			for (ActionDataKeeper actionData : actions) {
				this.actionData = actionData;
				actionExecutor = new ActionExecutorFactory(socketData,
						actionData).defineAndCreateActionExecutor();
				defineIfNewSessionIsNeededAndReopenIfNeeded();
				actionExecutor.executeInExistingSession(session);
			}
		}
		actionExecutor.closeSession(session);
		logger.info("Completed execution of action(s) on socket(s).");
	}

	private void defineIfNewSessionIsNeededAndReopenIfNeeded() {
		String currentSessionID = socketData.getHost() + "|"
				+ socketData.getPort() + "|" + actionData.getUser();
		if (!previousSessionID.equals(currentSessionID)) {
			if (session != null) {
				actionExecutor.closeSession(session);
			}
			session = actionExecutor.openSession();
			previousSessionID = currentSessionID;
		}
	}

}
